#include <stdio.h>
#include "key.h"


void key_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    __HAL_RCC_GPIOE_CLK_ENABLE();

    GPIO_InitStruct.Pin = KEY0_PIN|KEY1_PIN|KEY2_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);

    printf("key_init\r\n");

    // HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0);
    // HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);
}

uint8_t key_state = KEY_RELEASE;
int32_t pwm_duty_temp = 0;
// 按键拉低为按下
key_value_t key_scan(void)
{
    uint8_t keyvalue = KEY_NONE;
    uint8_t key0,key1,key2;
    
    key0 = HAL_GPIO_ReadPin(KEY0_PORT, KEY0_PIN);
    key1 = HAL_GPIO_ReadPin(KEY1_PORT, KEY1_PIN);
    key2 = HAL_GPIO_ReadPin(KEY2_PORT, KEY2_PIN);

    // printf("key0:%d,key1:%d,key2:%d\r\n",key0,key1,key2);
    if(key0 == 0 || key1 == 0 || key2 == 0)
    {
        if(key_state == KEY_RELEASE)//只有原先是松开的，后按下认为是按下
        {
            key_state = KEY_PRESS;
            //不支持多按键，如果多个按键同时按下，则返回最小的按键
            if(key0 == 0)
            {
                keyvalue = KEY_0;
            }
            else if(key1 == 0)
            {
                keyvalue = KEY_1;
            }
            else if(key2 == 0)
            {
                keyvalue = KEY_2;
            }
            printf("keyvalue:%d\r\n",keyvalue);
        }
        
    } 
    else 
    {
        key_state = KEY_RELEASE;
    }

    return keyvalue;
}
